'use client';

import { useState, useEffect } from 'react';
import { Box, Button, Typography, Container, Dialog, DialogTitle, DialogContent, DialogActions, Alert, Snackbar, IconButton } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import BarChartIcon from '@mui/icons-material/BarChart';
import { examApi } from '@/api/exams';
import ExamForm from '@/components/ExamForm';
import { useRouter } from 'next/navigation';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { useForm } from 'react-hook-form';
import dayjs from 'dayjs';

interface Exam {
  id: number;
  title: string;
  description: string;
  duration: number;
  startTime: string;
  endTime: string;
  totalScore: number;
  passingScore: number;
  questions: []
}

export default function ExamsPage() {
  const [exams, setExams] = useState<Exam[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingExam, setEditingExam] = useState<Exam | null>(null);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const router = useRouter();
  const { reset } = useForm();
  const [userRole, setUserRole] = useState<string>('');

  useEffect(() => {
    // 检查用户角色并获取考试列表
    const user = localStorage.getItem('user');
    if (user) {
      const userData = JSON.parse(user);
      setUserRole(userData.role);
      if (userData.role === 'TEACHER') {
        fetchExams();
      } else {
        router.push('/');
      }
    } else {
      router.push('/login');
    }
  }, [router]); // 只在组件挂载和路由变化时执行

  const fetchExams = async () => {
    try {
      setLoading(true);
      const data = await examApi.getAll();
      console.log(data);
      setExams(data);
    } catch (error) {
      setSnackbar({
        open: true,
        message: '获取考试列表失败',
        severity: 'error'
      });
    } finally {
      setLoading(false);
    }
  };

  const columns: GridColDef[] = [
    { field: 'id', headerName: 'ID', width: 70, headerAlign: 'center', align: 'center' },
    { field: 'title', headerName: '考试标题', width: 120, headerAlign: 'center', align: 'center' },
    { field: 'subject', headerName: '科目', width: 80, headerAlign: 'center', align: 'center' },
    { field: 'duration', headerName: '时长(分钟)', width: 100, headerAlign: 'center', align: 'center' },
    { 
      field: 'startTime', 
      headerName: '开始时间', 
      width: 180,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => {
        try {
          return params.value ? dayjs(params.value).format('YYYY-MM-DD HH:mm:ss') : '-';
        } catch (error) {
          console.error('日期格式化错误:', error);
          return '-';
        }
      }
    },
    { 
      field: 'endTime', 
      headerName: '结束时间', 
      width: 180,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => {
        try {
          return params.value ? dayjs(params.value).format('YYYY-MM-DD HH:mm:ss') : '-';
        } catch (error) {
          console.error('日期格式化错误:', error);
          return '-';
        }
      }
    },
    {
      field: 'status',
      headerName: '考试状态',
      width: 130,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => <ExamStatus examId={params.row.id} />
    },
    {
      field: 'actions',
      headerName: '操作',
      width: 250,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => (
        <Box>
          <IconButton
            onClick={() => handleEdit(params.row)}
            color="primary"
            size="small"
            title="编辑"
          >
            <EditIcon />
          </IconButton>
          <IconButton
            onClick={() => handleDelete(params.row.id)}
            color="error"
            size="small"
            title="删除"
          >
            <DeleteIcon />
          </IconButton>
          <IconButton
            onClick={() => router.push(`/exams/${params.row.id}/statistics`)}
            color="info"
            size="small"
            title="统计分析"
          >
            <BarChartIcon />
          </IconButton>
        </Box>
      )
    }
  ];

  const handleGenerateQuestions = async (exam: Exam) => {
    try {
      const count = window.prompt('请输入需要随机抽取的题目数量：');
      if (count === null) return;

      const numCount = parseInt(count);
      if (isNaN(numCount) || numCount <= 0) {
        setSnackbar({
          open: true,
          message: '请输入有效的题目数量',
          severity: 'error'
        });
        return;
      }

      await examApi.generateQuestions(exam.id, {
        count: numCount,
        subject: exam.subject
      });

      setSnackbar({
        open: true,
        message: '随机抽题成功',
        severity: 'success'
      });

      // 刷新考试列表
      fetchExams();
    } catch (error) {
      setSnackbar({
        open: true,
        message: '随机抽题失败',
        severity: 'error'
      });
    }
  };

  const handleCreate = () => {
    setEditingExam(null);
    reset();
    setIsModalVisible(true);
  };

  const handleEdit = (exam: Exam) => {
    setEditingExam(exam);
    reset({
      title: exam.title,
      subject: exam.subject,
      description: exam.description,
      examTime: [dayjs(exam.startTime), dayjs(exam.endTime)],
      duration: exam.duration,
      totalScore: exam.totalScore,
      passingScore: exam.passingScore,
    });
    setIsModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这个考试吗？')) return;
    try {
      await examApi.delete(id);
      setSnackbar({ open: true, message: '删除考试成功', severity: 'success' });
      fetchExams();
    } catch (error) {
      setSnackbar({ open: true, message: '删除考试失败', severity: 'error' });
    }
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Container maxWidth="lg" sx={{ mt: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
          <Typography variant="h4" component="h1">
            考试管理
          </Typography>
          {userRole === 'TEACHER' && (
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={handleCreate}
            >
              创建考试
            </Button>
          )}
        </Box>

        <Box sx={{ height: 1000, width: '100%' }}>
          <DataGrid
            rows={exams}
            columns={columns}
            pageSize={10}
            rowsPerPageOptions={[10]}
            disableSelectionOnClick
            loading={loading}
          />
        </Box>

        <Dialog
          open={isModalVisible}
          onClose={() => {
            setIsModalVisible(false);
            setEditingExam(null);
            reset();
          }}
          maxWidth="md"
          fullWidth
        >
          <DialogTitle sx={{ m: 0, p: 2 }}>
            {editingExam ? '编辑考试' : '创建考试'}
            <IconButton
              aria-label="关闭"
              onClick={() => {
                setIsModalVisible(false);
                setEditingExam(null);
                reset();
              }}
              sx={{
                position: 'absolute',
                right: 8,
                top: 8,
                color: (theme) => theme.palette.grey[500]
              }}
            >
              <CloseIcon />
            </IconButton>
          </DialogTitle>
          <DialogContent>
            <ExamForm
              onFinish={async (values) => {
                try {
                  if (editingExam) {
                    await examApi.update(editingExam.id, values);
                    setSnackbar({ open: true, message: '更新考试成功', severity: 'success' });
                  } else {
                    await examApi.create(values);
                    setSnackbar({ open: true, message: '创建考试成功', severity: 'success' });
                  }
                  setIsModalVisible(false);
                  setEditingExam(null);
                  fetchExams();
                } catch (error) {
                  setSnackbar({ open: true, message: editingExam ? '更新考试失败' : '创建考试失败', severity: 'error' });
                }
              }}
              loading={loading}
              initialValues={editingExam ? {
                title: editingExam.title,
                subject: editingExam.subject,
                description: editingExam.description,
                examTime: [dayjs(editingExam.startTime), dayjs(editingExam.endTime)],
                duration: editingExam.duration,
                totalScore: editingExam.totalScore,
                passingScore: editingExam.passingScore,
                questions: editingExam.questions || []
              } : {
                duration: 60,
                totalScore: 100,
                passingScore: 60,
              }}
              submitText={editingExam ? '保存修改' : '创建考试'}
            />
          </DialogContent>
        </Dialog>

        <Snackbar
          open={snackbar.open}
          autoHideDuration={3000}
          onClose={() => setSnackbar({ ...snackbar, open: false })}
        >
          <Alert severity={snackbar.severity as any} sx={{ width: '100%' }}>
            {snackbar.message}
          </Alert>
        </Snackbar>
      </Container>
    </LocalizationProvider>
  );
}

const ExamStatus = ({ examId }: { examId: number }) => {
  const [status, setStatus] = useState('NOT_STARTED');

  useEffect(() => {
    const fetchStatus = async () => {
      try {
        const { status } = await examApi.getStatus(examId);
        setStatus(status);
      } catch (error) {
        console.error('获取考试状态失败:', error);
      }
    };
    fetchStatus();
  }, [examId]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'NOT_STARTED':
        return '#FFA500';
      case 'IN_PROGRESS':
        return '#4CAF50';
      case 'ENDED':
        return '#FF0000';
      default:
        return '#000000';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'NOT_STARTED':
        return '未开始';
      case 'IN_PROGRESS':
        return '进行中';
      case 'ENDED':
        return '已结束';
      default:
        return '未知';
    }
  };

  return (
    <Box
      sx={{
        color: getStatusColor(status),
        fontWeight: 'bold'
      }}
    >
      {getStatusText(status)}
    </Box>
  );
};